package day05;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Demo06 {
    public static void main(String[] args) throws Exception {
        /*
         * 有返回值的线程任务
         */
        ExecutorService pool = Executors.newFixedThreadPool(3);
        Future<Integer> future1 = pool.submit(new Task());
        Future<Integer> future2 = pool.submit(new Task());
        Future<Integer> future3 = pool.submit(new Task());
        System.out.println(future1.isDone());
        System.out.println(future2.isDone());
        System.out.println(future3.isDone());
        //get()方法是阻塞方法, 等到线程完成才继续执行
        int all = future1.get() + future2.get() + future3.get();
        System.out.println(all);
        System.out.println(future1.isDone());
        System.out.println(future2.isDone());
        System.out.println(future3.isDone());
        pool.shutdown();
    }
}

/**
 * 定义一个计算任务, 返回值的Integer
 */
class Task implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        int sum=0;
        for (int i=0; i<10; i++){
            sum+=i;
        }
        Thread.sleep(1000);
        System.out.println(Thread.currentThread()+" "+sum);
        return sum;
    }
}